/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package login;

import java.io.IOException;

import org.jdom2.Document;
import org.jdom2.Element;
import org.jdom2.output.Format;
import org.jdom2.output.XMLOutputter;

import java.awt.Color;
import java.awt.MouseInfo;
import java.awt.Point;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
import javax.swing.JEditorPane;
import javax.swing.JOptionPane;
import javax.swing.JScrollPane;
import javax.swing.event.HyperlinkListener;
import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;

import java.awt.Graphics;
import java.awt.Image;

import javax.swing.JFrame;
import javax.swing.JPanel;


/**
 *
 * @author FROSAS
 */
public class Logeo extends javax.swing.JFrame {
    
  //private String file=".\\OWL-OFL\\jhon\\uses.xml";
   
    Login conexion = new Login();
     InetAddress ip;
  Connection conn=conexion.conexion();
    Document document;
    int x, y;
   Image background;
    
    public void limpiar(){
    
    txtUsu.setText("");
    txtCon.setText("");
    
    }
    
    public Logeo() {
        setUndecorated(true);
        setBackground(new Color(0,0,0,0));
        setLocationRelativeTo(null);
        JPanelBackground a = new JPanelBackground();
        setContentPane(a);
        initComponents();   
        
        
//        setShape(new Ellipse2D.Double(0,0,this.getWidth(),this.getHeight()));
    }
    
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        lblMinizar = new javax.swing.JLabel();
        txtUsu = new javax.swing.JTextField();
        txtCon = new javax.swing.JPasswordField();
        lblUsu = new javax.swing.JLabel();
        jButton2 = new javax.swing.JButton();
        lblCerrar = new javax.swing.JLabel();
        lblCon = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("LOGIN");
        setName("JFrame"); // NOI18N
        addMouseMotionListener(new java.awt.event.MouseMotionAdapter() {
            public void mouseDragged(java.awt.event.MouseEvent evt) {
                formMouseDragged(evt);
            }
        });
        addMouseListener(new java.awt.event.MouseAdapter() {
            public void mousePressed(java.awt.event.MouseEvent evt) {
                formMousePressed(evt);
            }
        });

        lblMinizar.setForeground(new java.awt.Color(5, 0, 0));
        lblMinizar.setText("--");
        lblMinizar.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                lblMinizarMouseClicked(evt);
            }
        });

        txtUsu.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                txtUsuActionPerformed(evt);
            }
        });

        txtCon.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                txtConActionPerformed(evt);
            }
        });

        lblUsu.setForeground(new java.awt.Color(254, 254, 254));
        lblUsu.setText("Usuario");

        jButton2.setBackground(new java.awt.Color(55, 55, 55));
        jButton2.setForeground(new java.awt.Color(254, 254, 254));
        jButton2.setText("INGRESAR");
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton2ActionPerformed(evt);
            }
        });

        lblCerrar.setForeground(new java.awt.Color(1, 1, 1));
        lblCerrar.setText("X");
        lblCerrar.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                lblCerrarMouseClicked(evt);
            }
        });

        lblCon.setForeground(new java.awt.Color(254, 254, 254));
        lblCon.setText("Password");

        jLabel2.setFont(new java.awt.Font("Ubuntu", 0, 34)); // NOI18N
        jLabel2.setForeground(new java.awt.Color(56, 56, 56));
        jLabel2.setText("OWL");

        jLabel3.setFont(new java.awt.Font("Ubuntu", 0, 28)); // NOI18N
        jLabel3.setForeground(new java.awt.Color(254, 254, 254));
        jLabel3.setText("off");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(75, 75, 75)
                .addComponent(jLabel2)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(lblMinizar)
                        .addGap(27, 27, 27)
                        .addComponent(lblCerrar)
                        .addContainerGap())
                    .addGroup(layout.createSequentialGroup()
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(txtCon, javax.swing.GroupLayout.PREFERRED_SIZE, 186, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(jLabel3)
                                .addGap(198, 198, 198))
                            .addComponent(txtUsu, javax.swing.GroupLayout.PREFERRED_SIZE, 186, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addContainerGap(131, Short.MAX_VALUE))))
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(141, 141, 141)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jButton2, javax.swing.GroupLayout.PREFERRED_SIZE, 112, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(93, 93, 93)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(lblCon)
                            .addComponent(lblUsu))))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addContainerGap()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(lblMinizar)
                            .addComponent(lblCerrar)))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(25, 25, 25)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jLabel2)
                            .addComponent(jLabel3))))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 24, Short.MAX_VALUE)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(txtUsu, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(lblUsu))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(lblCon)
                    .addComponent(txtCon, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(30, 30, 30)
                .addComponent(jButton2, javax.swing.GroupLayout.PREFERRED_SIZE, 33, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(31, 31, 31))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
             
                   acceder(txtUsu.getText(),txtCon.getText());
                    limpiar();
// TODO add your handling code here:
    }//GEN-LAST:event_jButton2ActionPerformed

    private void txtConActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txtConActionPerformed
      
    }//GEN-LAST:event_txtConActionPerformed

    private void txtUsuActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txtUsuActionPerformed
 
    }//GEN-LAST:event_txtUsuActionPerformed

    private void lblCerrarMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_lblCerrarMouseClicked
        System.exit(0);
    }//GEN-LAST:event_lblCerrarMouseClicked

    private void formMouseDragged(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_formMouseDragged
        Point point = MouseInfo.getPointerInfo().getLocation(); 
        this.setLocation(point.x - x, point.y - y); 
    }//GEN-LAST:event_formMouseDragged

    private void formMousePressed(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_formMousePressed
        x = evt.getX(); 
        y = evt.getY();
    }//GEN-LAST:event_formMousePressed

    private void lblMinizarMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_lblMinizarMouseClicked
        this.setExtendedState(ICONIFIED);
    }//GEN-LAST:event_lblMinizarMouseClicked

    public void llamarExplorador(){
    
     
        JFrame frame = new JFrame("Navegador .:. JAVA");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    try {

     //  JEditorPane editorPane = new JEditorPane("file:///C:/Users/FROSAS/Desktop/JAVA%20PROJECTS/Login/OWL-OFL/index.html");
      JEditorPane editorPane = new JEditorPane("file:///home/ghondar/Escritorio/JAVA_PROJECTS/Login/OWL-OFL/index.html");
      editorPane.setEditable(false);

      HyperlinkListener hyperlinkListener = new ActivatedHyperlinkListener(
          editorPane);
      editorPane.addHyperlinkListener(hyperlinkListener);

      JScrollPane scrollPane = new JScrollPane(editorPane);
      frame.add(scrollPane);
    } catch (IOException e) {
      System.err.println("Unable to load: " + e);
    }

    frame.setSize(1000, 700);
    frame.setVisible(true);
    frame.setLocationRelativeTo(frame);
    
    }

    public void creaDire(String user) {
        File directorio2 = new File("/home/ghondar/Escritorio/JAVA_PROJECTS/Login/OWL-OFL/");
        if (directorio2.mkdirs())
          System.out.println("Se ha creado directorio");
        else
          System.out.println("No se ha podido crear el directorio 2"); 
//     File directorio = new File("C:\\Users\\FROSAS\\Desktop\\JAVA PROJECTS\\Login\\OWL-OFL\\"+user+"");
        File directorio = new File("/home/ghondar/Escritorio/JAVA_PROJECTS/Login/OWL-OFL/"+user);

        if (directorio.mkdir())
          System.out.println("Se ha creado directorio");
        else
          System.out.println("No se ha podido crear el directorio 1");		
	}
    
   public void getXML(String user,String pass )
    {
        Document doc = new Document();
      
      
        Element root = new Element("DataBase");
        doc.setRootElement(root);
        try {
            
            String q = "SELECT * FROM usuarios WHERE usuario='"+user+"' && contra='"+pass+"'";
            Statement stmt = conn.createStatement();
            ResultSet resultset = stmt.executeQuery(q);
            ResultSetMetaData resultmetadata = resultset.getMetaData();
         
            int numCols = resultmetadata.getColumnCount();
            while (resultset.next()) {
                List elmts = new ArrayList();
                for (int i=1; i <= numCols; i++) {
                  
                    String colName = resultmetadata.getColumnName(i);                    
                   
                    String colVal = resultset.getString(i);                    
                   
                    Element elmt = new Element(colName);
                    elmt.setText(colVal);
                    elmts.add(elmt);
                }
               
                Element row = new Element("registro");
  
                row.setContent(elmts);
                root.addContent(row);                
            }
           
            resultset.close();
            stmt.close();
            
         
            XMLOutputter outputter = new XMLOutputter( Format.getPrettyFormat());
            try {
                
               outputter.output(doc, new FileOutputStream ( "/home/ghondar/Escritorio/JAVA_PROJECTS/Login/OWL-OFL/"+user+"/uses.xml"));
               System.out.println("Arhivo XML creado en " + "/home/ghondar/Escritorio/JAVA_PROJECTS/Login/OWL-OFL/"+user+"/uses.xml");
            }
            catch (IOException e) {
                System.out.println(e);
            }
        } catch (SQLException e) {
               System.err.println(e);
        }
    }
      
  private void insertPc(String user,String pass) {
      
        String sql="SELECT idusu FROM usuarios WHERE usuario='"+user+"' && contra='"+pass+"' ";
             
        try {
            
            Statement st = conn.createStatement();
            ResultSet rs = st.executeQuery(sql);            
            rs.next();
            String id = rs.getString("idusu");
            
            ip = InetAddress.getLocalHost(); 
            System.out.println("Dirección IP  : " + ip.getHostAddress()); 
            System.out.println("Hostname  : " + ip.getHostName());

            NetworkInterface network = NetworkInterface.getByInetAddress(ip); 
            byte[] mac = network.getHardwareAddress(); 

            System.out.print("Dirección MAC  : "); 

            StringBuilder sb = new StringBuilder(); 
            for (int i = 0; i < mac.length; i++) { 
                sb.append(String.format("%02X%s", mac[i], (i < mac.length - 1) ? "-" : "")); 
            } 
        
            System.out.println(sb.toString()); 

             PreparedStatement ps = conn.prepareStatement("UPDATE ParqueServer SET mac_usu= ?, ip_usu= ? WHERE id_usu='"+id+"'" );

            ps.setString(1, sb.toString());
            ps.setString(2,ip.getHostAddress());

            ps.executeUpdate();
           
           // conn.close();
        } catch (SQLException e) {
            e.printStackTrace();
            
        } catch (UnknownHostException e) { 

        e.printStackTrace(); 

    }
        catch (SocketException e){ 

        e.printStackTrace(); 

    } 
    }
   
    public void acceder(String usuario, String pass)
    {
        String cap="";
   
       String sql="SELECT * FROM usuarios WHERE usuario='"+usuario+"' && contra='"+pass+"'";
        try {
            Statement st = conn.createStatement();
            ResultSet rs = st.executeQuery(sql);
            
             rs.last();
              int encontrado=rs.getRow();
                                            
            if(encontrado==1)
            { 
                  this.setVisible(false);
                    JOptionPane.showMessageDialog(null, "Bienvenido al Sistema");
                    creaDire(usuario);
                    getXML(usuario,pass);
                   archivoXml(usuario);
                     insertPc(usuario,pass);
                  llamarExplorador();
              
                         }
            
            else if((!cap.equals("Administrador"))&& (!cap.equals("Invitado")))
            {
                JOptionPane.showMessageDialog(this, "NO EXISTE SUS DATOS");
            }
            
            
        } catch (SQLException ex) {
            JOptionPane.showMessageDialog(this, "ERROR DE CONEXION CON LA BASE DE DATOS");
        }
       
        }
      
    public void archivoXml(String usua){
    
    String server = "ftp.pollitoasado.com";
		int port = 21;
		String user = "prueba@pollitoasado.com";
		String pass = "@prueba@";
                
		FTPClient ftpClient = new FTPClient();
		try {

			ftpClient.connect(server, port);
			ftpClient.login(user, pass);
			ftpClient.enterLocalPassiveMode();

			ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
	
			File firstLocalFile =
//                   new File("C:\\Users\\FROSAS\\Desktop\\JAVA PROJECTS\\Login\\OWL-OFL\\"+usua+"\\uses.xml");
                             new File("/home/ghondar/Escritorio/JAVA_PROJECTS/Login/OWL-OFL/"+usua+"/uses.xml");
                        

			String firstRemoteFile = "uses.xml";
			InputStream inputStream = new FileInputStream(firstLocalFile);

			boolean done = ftpClient.storeFile(firstRemoteFile, inputStream);
			inputStream.close();
			if (done) {
                            
                          JOptionPane.showMessageDialog(null, "Archivo subido correctamente");  
			}
                        
			
	        inputStream.close();
	      

		} catch (IOException ex) {
			System.out.println("Error: " + ex.getMessage());
			ex.printStackTrace();
		} finally {
			try {
				if (ftpClient.isConnected()) {
					ftpClient.logout();
					ftpClient.disconnect();
				}
			} catch (IOException ex) {
				ex.printStackTrace();
			}
		}
    
    }
  
    

        
    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Windows".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(Logeo.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(Logeo.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(Logeo.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(Logeo.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>
        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new Logeo().setVisible(true);
            }
        });
    }
public class JPanelBackground extends JPanel {
 
	Image image;  
        public JPanelBackground()  
        {  
            setBackground(new Color(0,0,0,0));
            try  
            {  
                image = javax.imageio.ImageIO.read(new java.net.URL(getClass().getResource("/images/1.png"), "1.png"));  
            }  
            catch (Exception e) { /*handled in paintComponent()*/ }  
        }  
  
        @Override  
        protected void paintComponent(Graphics g)  
        {  
        super.paintComponent(g);   
        if (image != null)  
            g.drawImage(image, 0,0,this.getWidth(),this.getHeight(),this);  
        }  
 
}
    

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButton2;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel lblCerrar;
    private javax.swing.JLabel lblCon;
    private javax.swing.JLabel lblMinizar;
    private javax.swing.JLabel lblUsu;
    private javax.swing.JPasswordField txtCon;
    private javax.swing.JTextField txtUsu;
    // End of variables declaration//GEN-END:variables
}
